package cn.caplike.demo.repository.java.concurrency;

import java.util.concurrent.CompletableFuture;

/**
 * @author LiKe
 * @version 1.0.0
 * @date 2022-04-07 19:45
 * @see <a href="https://www.liaoxuefeng.com/wiki/1252599548343744/1306581182447650">使用CompletableFuture</a>
 */
@SuppressWarnings("ALL")
public class CompletableFutureDemo01 {

    public static void main(String[] args) throws Exception {
        // 第一个任务:
        CompletableFuture<String> cfQuery = CompletableFuture.supplyAsync(() -> {
            return queryCode("中国石油");
        });
        // cfQuery成功后继续执行下一个任务:
        CompletableFuture<Double> cfFetch = cfQuery.thenApplyAsync((code) -> {
            return fetchPrice(code);
        });
        // cfFetch成功后打印结果:
        cfFetch.thenAccept((result) -> {
            System.out.println("result: " + result);
        });
        // 主线程不要立刻结束，否则CompletableFuture默认使用的线程池会立刻关闭:
        Thread.sleep(Long.MAX_VALUE);
    }

    static String queryCode(String name) {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
        }
        System.out.println("code: " + "601857");
        return "601857";
    }

    static Double fetchPrice(String code) {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
        }
        final double price = 5 + Math.random() * 20;
        System.out.println("price: " + price);
        return price;
    }
}
